package com.cheneyjoo.dao;

import com.cheneyjoo.model.Exam;
import com.cheneyjoo.model.Question;
import com.cheneyjoo.util.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class ExamDao {
    private static List<Exam> examList = new ArrayList<>();

    /**
     * 初始化数据信息
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public ExamDao() throws IOException, ClassNotFoundException {
        File repositoryFile = Repository.getRepositoryFile("Exam.Exam.txt");
        if (examList.size() == 0 && repositoryFile.length() != 0) {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(repositoryFile));
            examList = (List<Exam>) ois.readObject();
            ois.close();
        }
    }

    /**
     * 获取试卷
     *
     * @param ID
     * @return
     */
    public Exam getExam(int ID) {
        Optional<Exam> exam = examList.stream().filter(s -> s.getId() == ID).findFirst();
        return exam.orElse(null);
    }

    /**
     * 获取全部试卷信息
     *
     * @return
     */
    public List<Exam> getExamList() {
        return examList;
    }

    /**
     * 添加试卷
     *
     * @param exam
     * @return
     */
    public boolean addExam(Exam exam) {
        Optional<Integer> max = examList.stream().map(s -> s.getId()).max((o1, o2) -> o1.compareTo(o2));
        exam.setId(max.orElse(0) + 1);
        exam.setStatus(0);
        examList.add(exam);
        FlushData();
        return true;
    }

    /**
     * 修改试卷信息
     *
     * @param exam
     * @return
     */
    public boolean updateExam(Exam exam) {
        Optional<Exam> examOptional = examList.stream().filter(s -> exam.getId() == s.getId()).findFirst();
        examOptional.ifPresent(s -> {
            if (Optional.ofNullable(exam.getCategoryName()).isPresent())
                s.setCategoryName(exam.getCategoryName());
            if (Optional.ofNullable(exam.getExamName()).isPresent())
                s.setExamName(exam.getExamName());
            if (Optional.ofNullable(exam.getQuestions()).isPresent()) {
                AtomicInteger id = new AtomicInteger();
                exam.getQuestions().forEach(a -> {
                    a.setId(id.get() + 1);
                    id.getAndIncrement();
                });
                s.setQuestions(exam.getQuestions());
            }
        });
        FlushData();
        return examOptional.isPresent();
    }

    /**
     * 修改试卷状态
     *
     * @param id
     * @param status
     * @return
     */
    public boolean updateStatus(int id, int status) {
        Optional<Exam> examOptional = examList.stream().filter(s -> id == s.getId()).findFirst();
        examOptional.ifPresent(s -> s.setStatus(status));
        FlushData();
        return examOptional.isPresent();
    }

    /**
     * 删除试卷
     *
     * @param id
     * @return
     */
    public boolean deleteExam(int id) {
        boolean remove = examList.remove(examList.stream().filter(s -> id == s.getId()).findFirst().orElse(null));
        if (remove) {
            FlushData();
        }
        return remove;
    }

    /**
     * 获取试卷的试题
     *
     * @param id
     * @return
     */
    public List<Question> getQuestions(int id) {
        return examList.stream().filter(s -> s.getId() == id).map(Exam::getQuestions).findFirst().orElse(null);
    }

    /**
     * 获取一条试题信息
     *
     * @param examID
     * @param questionID
     * @return
     */
    public Question getQuestion(int examID, int questionID) {
        Optional<List<Question>> questions = examList.stream().filter(s -> s.getId() == examID).map(Exam::getQuestions).findFirst();
        if (questions.isPresent()) {
            return questions.get().stream().filter(s -> s.getId() == questionID).findFirst().orElse(null);
        } else {
            return null;
        }
    }

    /**
     * 修改试题
     *
     * @param examID
     * @param questionID
     * @param question
     * @return
     */
    public boolean updateQuestion(int examID, int questionID, Question question) {
        Optional<List<Question>> questions = examList.stream().filter(s -> s.getId() == examID).map(Exam::getQuestions).findFirst();
        if (questions.isPresent()) {
            Optional<Question> oldQuestion = questions.get().stream().filter(s -> s.getId() == questionID).findFirst();
            if (oldQuestion.isPresent()) {
                oldQuestion.get().setName(question.getName());
                oldQuestion.get().setRightAnswer(question.getRightAnswer());
                oldQuestion.get().setScore(question.getScore());
                oldQuestion.get().setAnswers(question.getAnswers());
            }
            FlushData();
        }
        return questions.isPresent();
    }

    /**
     * 删除试题
     *
     * @param examID
     * @param questionID
     * @return
     */
    public boolean deleteQuestion(int examID, int questionID) {
        Optional<List<Question>> questions = examList.stream().filter(s -> s.getId() == examID).map(Exam::getQuestions).findFirst();
        if (questions.isPresent()) {
            questions.ifPresent(s -> s.remove(s.stream().filter(a -> a.getId() == questionID).findFirst().orElse(null)));
            FlushData();
        }
        return true;
    }

    /**
     * 根据状态获取试卷信息
     * @param status
     * @return
     */
    public List<Exam> getExamByStatus(int status) {
        return examList.stream().filter(s -> s.getStatus() == status).collect(Collectors.toList());
    }

    /**
     * 刷新数据
     */
    private void FlushData() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Repository.getRepositoryFile("Exam.Exam.txt")));
            oos.writeObject(examList);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
